<?php

/**
 * @file
 * Definition of example_handler_custom_field
 */

/**
 * Provides a custom views field.
 */
class jessica_stylebook_handler_style_item_article_count extends views_handler_field {
    function option_definition() {
        $options = parent::option_definition();
        return $options;
    }

    function options_form(&$form, &$form_state) {
        parent::options_form($form, $form_state);
    }

    function query() {
        // do nothing -- to override the parent query.
    }

    function render($data) {
        //dpm($data, 'latest data');

        $query = 'SELECT
          count(node_article.nid) as count
        FROM
            {node} n
        LEFT JOIN
            {field_data_field_styling_item_id} ss_id
        ON
            (ss_id.field_styling_item_id_target_id = n.nid)
        LEFT JOIN
            {field_data_field_styling_item} si
        ON
            (si.field_styling_item_value = ss_id.entity_id)
        LEFT JOIN
            {node} node_article
        ON
            (node_article.nid = si.entity_id)
        WHERE
            n.type = :type
        AND
            n.nid = :nid
        AND
            node_article.status = 1';

        $result = db_query($query, array(':type' => 'xenyo_sc_styling_item', ':nid' => $data->nid));

        $count = 0;

        foreach ($result as $record) {
            $count = $record->count;
        }

        return '<span>' . $count . '</span>';
    }
}

